#include "usb_device.h"
#include "usb_com.h"
#include "string.h"
#include "usbd_customhid.h"
#include "func_uart.h"

uint8_t report[CUSTOM_HID_EPOUT_SIZE];
unsigned char chksum(unsigned char *b, int len)
{
    unsigned char sum = 0;
    for (int i = 0; i < len; i++)
    {
        sum += b[i];
    }
    return sum;
}


void usb_send(unsigned char *arr, unsigned short len)
{
    memset(report, 0, CUSTOM_HID_EPOUT_SIZE);
    memcpy(report, arr, len);
    USB_Send(report, CUSTOM_HID_EPOUT_SIZE);
}


void uart_func_cmd(unsigned char* message)
{
    switch (message[4])
    {
        case 0x01:
            uart_set_param(message);
            break;
        case 0x02:
            uart_send_data(message);
            break;

        default:
            break;
    }
}


void usb_rec(unsigned char *message, unsigned short len)
{
    if (len < 6)
    {
        return;
    }
    else
    {
        if (!((message[0] == 0xaa && message[1] == 0x55)||(message[0] == 0x55 && message[1] == 0xaa)) || message[2] > len)//data len error or header error
        {
            return;
        }
        if (message[message[2] - 1] != chksum(message, message[2] - 1)) // checksum error
        {
            return;
        }

        switch (message[3])
        {
            case 0x01:
                uart_func_cmd(message);
                break;

            default:
                break;
        }
    }
}

void usb_reply_ok(unsigned char cmd,unsigned char subCmd,unsigned char ok)
{
    unsigned char reply[7];
    reply[0] = 0xaa;
    reply[1] = 0x55;
    reply[2] = 7;
    reply[3] = cmd;
    reply[4] = subCmd;
    reply[5] = ok;
    reply[6] = chksum(reply,6);
    usb_send(reply,7);
}
